import request from '#/utils/requestAbort';
import moment from 'moment';

// MQTT主页面主题定义
export const MQTT_ENUM = {
  TRANSACTION_ADD_CONTRACT: `transaction_add_contract_${CLIENT_ENV}`, // 合约新增主题
  TRANSACTION_EDIT_CONTRACT: `transaction_edit_contract_${CLIENT_ENV}`, // 合约编辑主题
  TRANSACTION_DEL_CONTRACT: `transaction_del_contract_${CLIENT_ENV}`, // 删除合约
  TRANSACTION_EDIT_SYS_CONTRACT: `transaction_edit_sys_contract_${CLIENT_ENV}`,
  REMAINING_POSITIONS: `remaining_positions_${CLIENT_ENV}`, // 剩余仓位
  SETTLEMENT_UNIT: `settlement_unit_${CLIENT_ENV}`, // 结算单元
};

/** 对手方 */
export async function getCounterPartyList(id) {
  // 查询
  return request(`/disclosure/counterparty/getCounterPartyList`, {
    method: 'POST',
    data: {
      provinceId: id,
    },
  });
}
export async function addCounterParty(param) {
  // 新增
  return request(`/disclosure/counterparty/addCounterParty`, {
    method: 'POST',
    data: param,
  });
}
export async function delCounterPartyAndContracts(param) {
  // 删除
  return request(`/disclosure/counterparty/delCounterPartyAndContracts`, {
    method: 'POST',
    data: param,
  });
}

/** 仓位 */
export async function capacityForecastQuery(param) {
  // 产能预测
  return request(`/disclosure/powerForecastAdjustment/capacityForecastQuery`, {
    method: 'POST',
    data: param,
  });
}
// 合约
export async function getHomeStationContracts(param) {
  return request(`/disclosure/contract/getHomeStationContracts`, {
    method: 'POST',
    data: param,
  });
}
export async function getStationContracts(param) {
  return request(`/disclosure/contract/getStationContracts`, {
    method: 'POST',
    data: param,
  });
}
export async function queryRemainingPositions(param) {
  // 剩余仓位
  return request(`/disclosure/remainingPositions/queryRemainingPositions`, {
    method: 'POST',
    data: param,
  });
}
export async function getStationBenchmarkPrice(param) {
  // 基数合约电价
  return request(`/disclosure/benchmarkPrice/getStationBenchmarkPrice`, {
    method: 'POST',
    data: param,
  });
}

//编辑保存合约
export async function editSaveContract(param) {
  return request(`/disclosure/contractTimePeriod/editContractTimePeriod`, {
    method: 'POST',
    data: param,
  });
}

//新建保存合约
export async function saveAddContract(param) {
  return request(`/disclosure/contractTimePeriod/saveContractTimePeriod`, {
    method: 'POST',
    data: param,
  });
}

//保存
export async function dataSourceSave(params) {
  return request(`/disclosure/stationDatasource/dataSourceSave`, {
    method: 'POST',
    data: params,
  });
}

//仓位管理-主子页面-key值查询
export async function detailedQuery(param) {
  return request(`/disclosure/stationDatasource/detailedQuery`, {
    method: 'POST',
    data: param,
  });
}

//模板查询
export async function templateSearch() {
  return request(`/disclosure/periodTemplateMaster/templateListQuery`, {
    method: 'POST',
  });
}

export async function baseElectricity(param) {
  // 基数合约电量
  return request(`/disclosure/baseElectricity/baseElectricity`, {
    method: 'POST',
    data: param,
  });
}

export async function universalInterfaceExport(param) {
  return request(`/generation-common/universalInterface/csv/export`, {
    method: 'POST',
    data: param,
    responseType: 'blob',
    getResponse: true,
  });
}

// 根据引用合约信息获取list
export async function getContractTimeByCite(param) {
  return request(`/disclosure/contractTimePeriod/getContractTimePeriods`, {
    method: 'POST',
    data: param,
  });
}

//引用合约
export async function citeContractFn(param) {
  return request(`/disclosure/contract/refenceStationContracts`, {
    method: 'POST',
    data: param,
  });
}

//删除模板
export async function deleteTemplateFn(param) {
  return request(`/disclosure/periodTemplateMaster/templateDelete`, {
    method: 'POST',
    data: param,
  });
}

//修改模板名称
export async function editTemplateFn(param) {
  return request(`/disclosure/periodTemplateMaster/templateNameEdit`, {
    method: 'POST',
    data: param,
  });
}

//模板保存
export async function saveTemplateFn(param) {
  return request(`/disclosure/periodTemplateMaster/templateSave`, {
    method: 'POST',
    data: param,
  });
}

//时间段列表id查询
export async function timeQuanTunId(param) {
  return request(`/disclosure/periodTemplateMaster/timePeriodListByID`, {
    method: 'POST',
    data: param,
  });
}

export async function initFetch(param, stationMap, type = 'main') {
  const { startDate, endDate, settlementUnitList, counterpartyList } = param;
  // 参数处理
  const p1 = { startDate, endDate, settlementUnitList };
  const p2 = { ...p1, counterpartyList };
  // 两天之间的所有日期
  const diffDays = moment(endDate).diff(moment(startDate), 'day') + 1;
  const daysList = Array.from({ length: diffDays }, (__, i) =>
    moment(startDate).add(i, 'day').format('YYYY-MM-DD'),
  );
  // 并发http
  const [capacity, contract, remaining, basePrice, baseElect] = await Promise.all([
    capacityForecastQuery(p1),
    type === 'main' ? getHomeStationContracts(p2) : getStationContracts(p2),
    queryRemainingPositions(p1),
    getStationBenchmarkPrice(p2),
    baseElectricity(p1),
  ]);
  // console.log(capacity, contract, remaining, basePrice, baseElect)
  let result = corverAllContract({
    capacity: capacity?.body || {}, // 产能预测
    data: contract?.results || {}, // 所有合约
    remaining: remaining?.results || {}, // 剩余仓位
    basePrice: basePrice?.results || {}, // 基数合约电价
    baseElect: baseElect?.results || {}, // 基数合约电量
    daysList, // 两天之间的所有日期
    stationMap, // 场站映射，取名称
  });
  return Promise.resolve(result);
}

// 合约处理
function corverAllContract({
  baseElect,
  basePrice,
  capacity,
  data,
  daysList,
  remaining,
  stationMap,
}) {
  // 数据补全
  const transNum = (arr) => {
    return Array.from({ length: 96 }, (__, i) => {
      let item = arr?.[i];
      if (typeof item === 'string') return Number(item);
      if (typeof item === 'number') return item;
      return null;
    });
  };

  const getNums = (v, subKey) => {
    let res = {};
    daysList.map((day) => {
      res[day] = transNum(subKey ? v?.[day]?.[subKey] : v?.[day]);
    });
    return res;
  };

  // 按场返回
  return Object.entries(data).map(([staId, item]) => {
    let _temp = {
      stationId: staId,
      stationName: stationMap[staId],
      baseContract: {
        contractType: 'baseContract',
        contractName: '基础合约',
        price: getNums(basePrice?.[staId], 'points'),
        quantity: getNums(baseElect?.[staId]),
      },
      contracts: [], // 非基础合约
      capacity: getNums(capacity?.[staId], 'points'), // 产能预测
      remaining: getNums(remaining?.[staId]), // 剩余仓位
    };
    if (!item) return _temp;
    // 处理
    Object.values(item).map((n) => {
      let price = {},
        quantity = {};
      daysList.map((day) => {
        price[day] = transNum(n?.price?.[day]?.points);
        quantity[day] = transNum(n?.quantity?.[day]?.points);
      });
      _temp.contracts.push({
        ...n,
        price,
        quantity,
      });
    });
    return _temp;
  });
}

/** 预测数据源 */
export async function batchDataSourceSave(param) {
  // 保存
  return request(`/disclosure/stationDatasource/batchDataSourceSave`, {
    method: 'POST',
    data: param,
  });
}
export async function forecastDataSource(param) {
  // 查询
  return request(`/disclosure/powerForecastAdjustment/forecastDataSource`, {
    method: 'POST',
    data: param,
  });
}

// 省份-交易中心-场站（数据权限）
export async function queryMarketList(menuCode) {
  return request(`/power/dataPower/common/${menuCode}/t_station`, {
    method: 'GET',
  });
}
